//
//  NvTakeMediaViewController.m
//  NvSellerShow
//
//  Created by dx on 17/2/13.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvTakeMediaViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ZJSwitch.h"
#import "UIImage+Resize.h"
#import "UIKit+Ext.h"

@interface NvTakeMediaViewController ()
@property (weak, nonatomic) IBOutlet ZJSwitch *switchBtn;
//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property (nonatomic, strong) AVCaptureDevice *device;

//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property (nonatomic, strong) AVCaptureDeviceInput *input;

//输出图片
@property (nonatomic ,strong) AVCaptureStillImageOutput *imageOutput;

//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property (nonatomic, strong) AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property (nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic)AVCaptureStillImageOutput *ImageOutPut;
//当前摄像头方向
//    AVCaptureDevicePositionBack  后置摄像头
//    AVCaptureDevicePositionFront 前置摄像头
@property (nonatomic ,assign) AVCaptureDevicePosition currentDevicePosition;
@property (weak, nonatomic) IBOutlet UIButton *devicePositionChangeBtn;
@property (weak, nonatomic) IBOutlet UIButton *flashBtn;
@property (weak, nonatomic) IBOutlet UIButton *guideBtn;
@property (weak, nonatomic) IBOutlet UIButton *mediaTakeBtn;
@property (weak, nonatomic) IBOutlet UIButton *mediaCancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *mediaSureBtn;

@end

@implementation NvTakeMediaViewController
{
    BOOL _isflashOn;
    PHAsset *_imageAsset;
    UITapGestureRecognizer *tapGesture;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initSwitchBtn];
    _mediaTakeBtn.hidden = NO;
    _mediaSureBtn.hidden = YES;
    _mediaCancelBtn.hidden = YES;
    _focusView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    _focusView.layer.borderWidth = 1.0;
    _focusView.layer.borderColor =[UIColor yellowColor].CGColor;
    _focusView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_focusView];
    tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(focusGesture:)];
    [self.view addGestureRecognizer:tapGesture];
    _focusView.hidden = YES;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self cameraDistrict];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initSwitchBtn
{
    _switchBtn.style = ZJSwitchStyleBorder;
    _switchBtn.knobText = @"引导";
    _switchBtn.knobTextOnColor = [UIColor colorWithHexString:@"59BEE1"];
    _switchBtn.knobTextOffColor = [UIColor blackColor];
    _switchBtn.thumbTintColor = [UIColor whiteColor];
    
    _switchBtn.onTextColor = [UIColor colorWithHexString:@"59BEE1"];
    _switchBtn.onContentViewColor = [UIColor colorWithHexString:@"59BEE1"];
    _switchBtn.offContentViewColor = [UIColor blackColor];
    _switchBtn.on = NO;
    _switchBtn.hidden = YES;
}

- (void)cameraDistrict
{
    //    AVCaptureDevicePositionBack  后置摄像头
    //    AVCaptureDevicePositionFront 前置摄像头
    self.device = [self cameraWithPosition:AVCaptureDevicePositionBack];
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
    
    self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
    
    self.session = [[AVCaptureSession alloc] init];
    //     拿到的图像的大小可以自行设定
    //    AVCaptureSessionPreset320x240
    //    AVCaptureSessionPreset352x288
    //    AVCaptureSessionPreset640x480
    //    AVCaptureSessionPreset960x540
    //    AVCaptureSessionPreset1280x720
    //    AVCaptureSessionPreset1920x1080
    //    AVCaptureSessionPreset3840x2160
    self.session.sessionPreset = AVCaptureSessionPreset640x480;
    //输入输出设备结合
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.imageOutput]) {
        [self.session addOutput:self.imageOutput];
    }
    //预览层的生成
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, self.mediaView.width_LL, self.mediaView.height_LL);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
//    self.previewLayer.videoGravity = AVLayerVideoGravityResize;
    [self.mediaView.layer insertSublayer:self.previewLayer below:self.guideImageView.layer];
    
    //设备取景开始
    [self.session startRunning];
    if ([_device lockForConfiguration:nil]) {
        //自动闪光灯，
        if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [_device setFlashMode:AVCaptureFlashModeAuto];
        }
        //自动白平衡,但是好像一直都进不去
        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [_device unlockForConfiguration];
    }
}

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position ){
            return device;
        }
    return nil;
}
- (IBAction)takeMediaBtnPressed:(id)sender {
    [self photoBtnDidClick];
    self.mediaTakeBtn.hidden = YES;
}

- (AVCaptureVideoOrientation) videoOrientationFromCurrentDeviceOrientation {
    switch ([[UIDevice currentDevice] orientation]) {
        case UIDeviceOrientationPortrait: {
            return AVCaptureVideoOrientationPortrait;
        }
        case UIDeviceOrientationLandscapeLeft: {
            return AVCaptureVideoOrientationLandscapeRight;
        }
        case UIDeviceOrientationLandscapeRight: {
            return AVCaptureVideoOrientationLandscapeLeft;
        }
        case UIDeviceOrientationPortraitUpsideDown: {
            return AVCaptureVideoOrientationPortraitUpsideDown;
        }
        default:
            return AVCaptureVideoOrientationPortrait;
        //此处UIDeviceOrientationLandscapeLeft对应AVCaptureVideoOrientationLandscapeRight为iosSDK问题，并非编写错误
    }
}

- (void)photoBtnDidClick
{

    AVCaptureConnection *conntion = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
    if (!conntion)
    {
        NSLog(@"拍照失败!");
        return;
    }
    AVCaptureVideoOrientation orientation = [self videoOrientationFromCurrentDeviceOrientation];
    if(orientation >= 0)
        [conntion setVideoOrientation:orientation];
    [self.imageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
    {
        if (imageDataSampleBuffer == nil)
        {
            NSLog(@"imageDataSampleBuffer is nil");
            return ;
        }
        [self.session stopRunning];
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        self.image = [UIImage imageWithData:imageData];
        UIImage *image = [self.image normalizedImage];
        self.image = [UIImage handleImage:image withSize:_mediaView.size_LL];
        [self.previewImageView setImage:self.image];
        self.previewImageView.hidden = NO;
        _mediaCancelBtn.hidden = NO;
        _mediaSureBtn.hidden = NO;
    }];

}

- (void)changeCamera{
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        NSError *error;
        //给摄像头的切换添加翻转动画
        CATransition *animation = [CATransition animation];
        animation.duration = .5f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.type = @"oglFlip";
        
        AVCaptureDevice *newCamera = nil;
        AVCaptureDeviceInput *newInput = nil;
        //拿到另外一个摄像头位置
        AVCaptureDevicePosition position = _currentDevicePosition;
        if (position == AVCaptureDevicePositionFront){
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            animation.subtype = kCATransitionFromLeft;//动画翻转方向
            _currentDevicePosition = AVCaptureDevicePositionBack;
        }
        else {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            animation.subtype = kCATransitionFromRight;//动画翻转方向
            _currentDevicePosition = AVCaptureDevicePositionFront;
        }
        //生成新的输入
        newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
        [self.previewLayer addAnimation:animation forKey:nil];
        if (newInput != nil) {
            [self.session beginConfiguration];
            [self.session removeInput:self.input];
            if ([self.session canAddInput:newInput]) {
                [self.session addInput:newInput];
                self.input = newInput;
                
            } else {
                [self.session addInput:self.input];
            }
            [self.session commitConfiguration];
            
        } else if (error) {
            NSLog(@"toggle carema failed, error = %@", error);
        }  
    }  
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)backBtnPressed:(id)sender {
    [self dismissViewControllerAnimated:NO completion:nil];
}
- (IBAction)changeCamaraBtnPressed:(id)sender {
    [self changeCamera];
    if(_currentDevicePosition ==  AVCaptureDevicePositionBack)
    {
        [_devicePositionChangeBtn setImage:[self imageFromBundle:@"cam_turnoff"]forState:UIControlStateNormal];
    }
    else
    {
        [_devicePositionChangeBtn setImage:[self imageFromBundle:@"cam_turnon"] forState:(UIControlStateNormal) ];
    }
    
}
- (IBAction)guideBtnPressed:(id)sender {
    if(_guideImageView.hidden)
    {
        _guideImageView.hidden = NO;
        [_guideBtn setImage:[self imageFromBundle:@"cam_guideon"] forState:UIControlStateNormal];
    }
    else
    {
        _guideImageView.hidden = YES;
        [_guideBtn setImage:[self imageFromBundle:@"cam_guideoff"] forState:UIControlStateNormal];
        
    }
}

- (IBAction)flashBtnPressed:(id)sender {
    if ([_device lockForConfiguration:nil]) {
        if (_isflashOn) {
            if ([_device isFlashModeSupported:AVCaptureFlashModeOff]) {
                [_device setFlashMode:AVCaptureFlashModeOff];
                _isflashOn = NO;
                [_flashBtn setImage:[self imageFromBundle:@"cam_flashoff"] forState:UIControlStateNormal];
            }
        }else{
            if ([_device isFlashModeSupported:AVCaptureFlashModeOn]) {
                [_device setFlashMode:AVCaptureFlashModeOn];
                _isflashOn = YES;
                [_flashBtn setImage:[self imageFromBundle:@"cam_flashon"] forState:UIControlStateNormal];
            }
        }
        
        [_device unlockForConfiguration];
    }
}

#pragma mark - 保存照片
- (void)saveCamera
{
    [self saveImageToPhotoAlbum:self.image];
    [self.view insertSubview:_mediaView belowSubview:_mediaTakeBtn];
    self.mediaView.layer.masksToBounds = YES;
    NSLog(@"image size = %@",NSStringFromCGSize(self.image.size));
}

#pragma - 保存至相册

- (void)saveImageToPhotoAlbum:(UIImage*)savedImage
{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(globalQueue, ^(void) {
        NSMutableArray *imageIds = [NSMutableArray array];
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    
                    //写入图片到相册
                    PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:self.image];
                    //记录本地标识，等待完成后取到相册中的图片对象
                    [imageIds addObject:req.placeholderForCreatedAsset.localIdentifier];
                    
                    
                } completionHandler:^(BOOL success, NSError * _Nullable error) {
                    
                    NSLog(@"success = %d, error = %@", success, error);
                    
                    if (success)
                    {
                        //成功后取相册中的图片对象
                        PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:imageIds options:nil];
                        [result enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            
                            _imageAsset = obj;
                            *stop = YES;
                    
                            
                        }];
                    }
                    dispatch_semaphore_signal(sema);
                }];
            } else {
                //保存不了
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无法访问相册，照片保存失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                    [alert show];
                });
                
                dispatch_semaphore_signal(sema);
            }
        }];
        
    });
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    [self dismissViewControllerAnimated:YES completion:^(){
        if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishTakeMedia:)] ==YES) {
            [self.delegate didFinishTakeMedia:_imageAsset];
        }
    }];
}

-(void)cancel{
    [self.previewImageView setImage:nil];
    [self.previewImageView setHidden:YES];
    [self.session startRunning];
}

- (IBAction)mediaCancelBtnPressed:(id)sender {
    [self cancel];
    _mediaCancelBtn.hidden = YES;
    _mediaSureBtn.hidden = YES;
    self.mediaTakeBtn.hidden = NO;
}
- (IBAction)mediaSureBtnPressed:(id)sender {
    
    [self saveCamera];
    
    _mediaCancelBtn.hidden = YES;
    _mediaSureBtn.hidden = YES;
//    [self dismissViewControllerAnimated:NO completion:^(){
//        if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishTakeMedia:)] ==YES) {
//            [self.delegate didFinishTakeMedia:_imageAsset];
//        }
//    }];
    
}

- (void)focusGesture:(UITapGestureRecognizer*)gesture{
    CGPoint point = [gesture locationInView:gesture.view];
    CGRect rect = _mediaView.frame;
    if(CGRectContainsPoint(rect,point))
    {
        [self focusAtPoint:point];
    }
}
- (void)focusAtPoint:(CGPoint)point{
    CGSize size = self.view.bounds.size;
    CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
    NSError *error;
    if ([self.device lockForConfiguration:&error]) {
        
        if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            [self.device setFocusPointOfInterest:focusPoint];
            [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
        }
        
        if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
            [self.device setExposurePointOfInterest:focusPoint];
            [self.device setExposureMode:AVCaptureExposureModeAutoExpose];
        }
        
        [self.device unlockForConfiguration];
        _focusView.center = point;
        _focusView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{
                _focusView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                _focusView.hidden = YES;
            }];
        }];
    }
    
}

- (UIImage *)imageFromBundle:(NSString*)imageName {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    NSString *imagePath = [myBundle pathForResource:imageName ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    return image;
}

@end

